package com.ffcc.fitness.order.service.impl;

import com.ffcc.fitness.order.mapper.OrderMapper;
import com.ffcc.fitness.order.pojo.dto.OrderCreateParam;
import com.ffcc.fitness.order.pojo.dto.OrderStatusUpdateParam;
import com.ffcc.fitness.order.pojo.entity.Order;
import com.ffcc.fitness.order.pojo.vo.OrderVO;
import com.ffcc.fitness.order.service.OrderService;
import com.ffcc.fitness.user.mapper.UserMapper;
import com.ffcc.fitness.user.pojo.vo.UserVO;
import com.ffcc.fitness.websocket.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private ChatService chatService;
    
    @Override
    @Transactional
    public OrderVO createOrder(OrderCreateParam orderCreateParam) {
        log.info("创建订单，参数：{}", orderCreateParam);
        
        // 检查买家地址
        if (!checkUserAddress(orderCreateParam.getBuyerId())) {
            throw new RuntimeException("用户未设置地址，请先完善个人信息");
        }
          // 创建订单实体
        Order order = new Order();
        order.setTradeId(orderCreateParam.getTradeId());
        order.setBuyerId(orderCreateParam.getBuyerId());
        order.setSellerId(orderCreateParam.getSellerId());
        order.setEquipmentName(orderCreateParam.getEquipmentName());
        order.setQuantity(orderCreateParam.getQuantity());
        order.setPrice(orderCreateParam.getPrice());
        
        // 计算总金额
        BigDecimal totalAmount = orderCreateParam.getPrice().multiply(new BigDecimal(orderCreateParam.getQuantity()));
        order.setTotalAmount(totalAmount);
        
        // 设置订单状态为待确认
        order.setStatus(Order.Status.PENDING);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        // 保存订单
        int result = orderMapper.insert(order);
        if (result <= 0) {
            throw new RuntimeException("订单创建失败");
        }
        
        // 创建聊天会话并发送订单信息
        createChatWithOrderInfo(orderCreateParam.getBuyerId(), orderCreateParam.getSellerId(), 
                              orderCreateParam.getEquipmentName(), totalAmount);
        
        // 转换为VO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        
        log.info("订单创建成功，订单ID：{}", order.getOrderId());
        return orderVO;
    }
    
    @Override
    public List<OrderVO> getOrdersByBuyerId(Long buyerId) {
        log.info("查询买家订单列表，买家ID：{}", buyerId);
        return orderMapper.selectByBuyerId(buyerId);
    }
    
    @Override
    public List<OrderVO> getOrdersBySellerId(Long sellerId) {
        log.info("查询卖家订单列表，卖家ID：{}", sellerId);
        return orderMapper.selectBySellerId(sellerId);
    }
    
    @Override
    @Transactional
    public void updateOrderStatus(OrderStatusUpdateParam updateParam) {
        log.info("更新订单状态，参数：{}", updateParam);
        
        int result = orderMapper.updateStatus(updateParam.getOrderId(), updateParam.getStatus());
        if (result <= 0) {
            throw new RuntimeException("订单状态更新失败");
        }
        
        log.info("订单状态更新成功，订单ID：{}，新状态：{}", updateParam.getOrderId(), updateParam.getStatus());
    }
    
    @Override
    public boolean checkUserAddress(Long userId) {
        log.info("检查用户地址，用户ID：{}", userId);
        
        UserVO user = userMapper.selectByUserId(userId);
        if (user == null) {
            log.warn("用户不存在，用户ID：{}", userId);
            return false;
        }
        
        boolean hasAddress = user.getAddress() != null && !user.getAddress().trim().isEmpty();
        log.info("用户地址检查结果，用户ID：{}，有地址：{}", userId, hasAddress);
        
        return hasAddress;
    }    /**
     * 创建聊天会话并发送订单信息
     */    private void createChatWithOrderInfo(Long buyerId, Long sellerId, String equipmentName, BigDecimal totalAmount) {
        try {
            log.info("=== 开始创建订单相关聊天会话 ===");
            log.info("买家ID：{}，卖家ID：{}，商品名称：{}，总金额：{}", buyerId, sellerId, equipmentName, totalAmount);
            System.out.println("=== 开始创建订单相关聊天会话 ===");
            System.out.println("买家ID：" + buyerId + "，卖家ID：" + sellerId + "，商品名称：" + equipmentName + "，总金额：" + totalAmount);
            
            // 创建或获取聊天会话
            chatService.createOrGetChat(buyerId, sellerId, null, equipmentName);
            System.out.println("聊天会话创建/获取完成");            // 发送简洁文本格式的订单信息消息
            String orderMessage = String.format(
                "📋 新订单通知\n" +
                "商品：%s\n" +
                "金额：¥%.2f\n" +
                "状态：待确认\n" +
                "时间：%s\n\n" +
                "请及时处理订单，买家正在等待您的确认",
                equipmentName, 
                totalAmount, 
                LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm"))
            );
            System.out.println("=== 准备发送订单消息 ===");
            System.out.println("消息内容：" + orderMessage);
            System.out.println("发送者ID（买家）：" + buyerId + "，接收者ID（卖家）：" + sellerId);
            
            chatService.sendMessage(buyerId, sellerId, orderMessage);
            
            System.out.println("=== 订单消息发送完成 ===");
            log.info("订单聊天会话创建成功");
        } catch (Exception e) {
            log.error("创建订单聊天会话失败", e);
            // 不抛出异常，避免影响订单创建
            
        }
    }
}
